package handel

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"post/api/inits"
	"post/internal/model"
	req2 "post/internal/req"
)

func LikeAdd(c *gin.Context) {
	var req req2.LikeAdd
	c.ShouldBind(&req)
	var like = model.Like{
		UserId: req.UserId,
		DistId: req.DistId,
		Status: "未点赞",
	}
	var tx = inits.DB.Debug().Begin()
	tx.Where("user_id = ?", req.UserId).Where("dist_id = ?", req.DistId).Find(&like)
	if like.ID == 0 {
		tx.Create(&like)
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "请再点击一次",
			"data":    like.ID,
		})
		tx.Commit()
	} else {
		if like.Status == "未点赞" {
			tx.Table("likes").Where("user_id = ?", req.UserId).Where("dist_id = ?", req.DistId).Update("status", "已点赞")
			tx.Table("pots").Where("id = ?", req.DistId).UpdateColumn("like_num", gorm.Expr("like_num + ?", 1))
			tx.Table("pots").Where("id = ?", req.DistId).UpdateColumn("hot_num", gorm.Expr("hot_num + ?", 1))
			c.JSON(http.StatusOK, gin.H{
				"code":    200,
				"message": "点赞成功",
				"data":    like.ID,
			})
			tx.Commit()
		} else {
			tx.Table("likes").Where("user_id = ?", req.UserId).Where("dist_id = ?", req.DistId).Update("status", "未点赞")
			tx.Table("pots").Where("id = ?", req.DistId).UpdateColumn("like_num", gorm.Expr("like_num - ?", 1))
			c.JSON(http.StatusOK, gin.H{
				"code":    200,
				"message": "取消点赞成功",
				"data":    like.ID,
			})
			tx.Commit()
		}
	}
}
